package com.jn.mvvm2.views;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.jn.mvvm2.R;
import com.jn.mvvm2.databinding.ItemPetBinding;
import com.jn.mvvm2.entity.Pet;

public class PetAdapter extends ListAdapter<Pet.PetDetails, PetAdapter.PetViewHolder> {
    private OnPetClickListener onPetClickListener;

    public PetAdapter(OnPetClickListener onPetClickListener) {
        super(DIFF_CALLBACK);
        this.onPetClickListener = onPetClickListener;
    }

    @NonNull
    @Override
    public PetViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemPetBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_pet, parent, false);
        return new PetViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull PetViewHolder holder, int position) {
        Pet.PetDetails pet = getItem(position);
        holder.bind(pet);
    }

    public interface OnPetClickListener {
        void onPetClick(Pet.PetDetails pet);
    }

    public static final DiffUtil.ItemCallback<Pet.PetDetails> DIFF_CALLBACK = new DiffUtil.ItemCallback<Pet.PetDetails>() {
        @Override
        public boolean areItemsTheSame(@NonNull Pet.PetDetails oldItem, @NonNull Pet.PetDetails newItem) {
            return oldItem.getUrl().equals(newItem.getUrl());
        }

        @Override
        public boolean areContentsTheSame(@NonNull Pet.PetDetails oldItem, @NonNull Pet.PetDetails newItem) {
            return oldItem.equals(newItem);
        }
    };

    public class PetViewHolder extends RecyclerView.ViewHolder {
        private ItemPetBinding binding;

        public PetViewHolder(@NonNull ItemPetBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        public void bind(Pet.PetDetails pet) {
            binding.setPet(pet);
            binding.getRoot().setOnClickListener(v -> onPetClickListener.onPetClick(pet));
        }
    }
}
